//
// Created by isabella on 25-6-22.
//
#include <common.h>

class Solution {
public:
    string solveEquation(string equation) {
        auto eqs = separateStrings(equation, '=');
        auto leq = calculate(eqs[0]);
        auto req = calculate(eqs[1]);

        int c = leq.first - req.first;
        int v = leq.second - req.second;

        if (c == 0 && v == 0) {
            return "Infinite solutions";
        } else if (v == 0) {
            return "No solution";
        }

        int res = -c / v;
        return "x=" + to_string(res);
    }

    //const,引用
    vector<string> separateStrings(const string &s, char token) {
        int begin = 0, end = s.find(token);
        vector<string> res;
        while (end != string::npos) {
            res.push_back(s.substr(begin, end - begin));
            begin = end + 1;
            end = s.find(token, begin);
        }
        res.push_back(s.substr(begin, end - begin));
        return res;
    }

    pair<int, int> calculate(string equation) {
        int constant = 0, variable = 0;
        deque<char> stk;

        bool sign_g = false;
        for (int i = 0; i < equation.size(); i++) {
            if (equation[i] == '+' || equation[i] == '-') {
                auto t = parse(stk, sign_g);
                constant += t.first;
                variable += t.second;
                if (equation[i] == '-') {
                    sign_g = true;
                } else {
                    sign_g = false;
                }
            } else {
                stk.push_back(equation[i]);
            }
        }

        auto t = parse(stk, sign_g);
        constant += t.first;
        variable += t.second;

        return make_pair(constant, variable);
    }

    pair<int, int> parse(deque<char> &stk, bool sign) {
        bool flag = false;
        if(stk.empty()) {
            return make_pair(0, 0);
        }
        if (stk.back() == 'x') {
            stk.pop_back();
            flag = true;
        }
        int c = 0;
        if (flag && stk.empty()) {
            c = 1;
        }
        while (!stk.empty()) {
            c*=10;
            c += stk.front() - '0';
            stk.pop_front();
        }
        if (sign) {
            c=-c;
        }
        if(flag) {
            return make_pair(0, c);
        }
        return make_pair(c, 0);
    }
};

int main() {
    Solution s;
    // auto res = s.solveEquation("-x=-1");
    auto res = s.solveEquation("x+5-3+x=6+x-2");
    cout << res << endl;
    return 0;
}
